<template>
  <view class="message-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="navbar-content">
        <text class="navbar-title">消息</text>
        <view class="navbar-right">
          <u-icon name="setting" color="white" size="20" @click="handleSettings"></u-icon>
        </view>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <scroll-view
      class="main-content"
      scroll-y
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 系统消息入口 -->
      <view class="system-messages modern-card">
        <view class="message-item" @click="handleSystemMessage">
          <view class="message-icon system">
            <u-icon name="bell-fill" color="white" size="20"></u-icon>
          </view>
          <view class="message-content">
            <text class="message-title">系统通知</text>
            <text class="message-desc">{{ systemMessagePreview }}</text>
          </view>
          <view class="message-meta">
            <u-badge :count="systemUnreadCount" :offset="[0, 0]" v-if="systemUnreadCount > 0"></u-badge>
            <u-icon name="arrow-right" color="#999" size="16"></u-icon>
          </view>
        </view>
      </view>

      <!-- 消息分类 -->
      <view class="message-categories">
        <view class="category-grid">
          <view class="category-item" @click="handleLikeMessages">
            <view class="category-icon like">
              <u-icon name="heart-fill" color="white" size="24"></u-icon>
            </view>
            <text class="category-title">点赞</text>
            <u-badge :count="likeUnreadCount" :offset="[-5, 5]" v-if="likeUnreadCount > 0"></u-badge>
          </view>

          <view class="category-item" @click="handleCommentMessages">
            <view class="category-icon comment">
              <u-icon name="chat-fill" color="white" size="24"></u-icon>
            </view>
            <text class="category-title">评论</text>
            <u-badge :count="commentUnreadCount" :offset="[-5, 5]" v-if="commentUnreadCount > 0"></u-badge>
          </view>

          <view class="category-item" @click="handleFollowMessages">
            <view class="category-icon follow">
              <u-icon name="account-fill" color="white" size="24"></u-icon>
            </view>
            <text class="category-title">关注</text>
            <u-badge :count="followUnreadCount" :offset="[-5, 5]" v-if="followUnreadCount > 0"></u-badge>
          </view>

          <view class="category-item" @click="handleAtMessages">
            <view class="category-icon at">
              <u-icon name="at" color="white" size="24"></u-icon>
            </view>
            <text class="category-title">@我的</text>
            <u-badge :count="atUnreadCount" :offset="[-5, 5]" v-if="atUnreadCount > 0"></u-badge>
          </view>
        </view>
      </view>

      <!-- 最近消息 -->
      <view class="recent-messages">
        <view class="section-header">
          <text class="section-title">最近消息</text>
          <text class="section-more" @click="handleAllMessages">查看全部</text>
        </view>

        <view class="message-list">
          <view
            class="message-item modern-card"
            v-for="message in recentMessages"
            :key="message.id"
            @click="handleMessageDetail(message)"
          >
            <view class="message-avatar">
              <u-avatar
                :src="message.userAvatar"
                size="45"
              ></u-avatar>
              <view class="message-type-badge" :class="message.type">
                <u-icon :name="getMessageTypeIcon(message.type)" color="white" size="12"></u-icon>
              </view>
            </view>

            <view class="message-content">
              <view class="message-header">
                <text class="message-username">{{ message.username }}</text>
                <text class="message-time">{{ formatTime(message.create_time) }}</text>
              </view>
              <text class="message-text">{{ getMessageText(message) }}</text>

              <!-- 消息预览内容 -->
              <view class="message-preview" v-if="message.relatedContent">
                <text class="preview-text">{{ message.relatedContent.content }}</text>
                <image
                  v-if="message.relatedContent.image"
                  :src="message.relatedContent.image"
                  class="preview-image"
                  mode="aspectFill"
                ></image>
              </view>
            </view>

            <view class="message-status">
              <view class="unread-dot" v-if="!message.isRead"></view>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="recentMessages.length === 0 && !loading">
        <u-icon name="chat" color="#ccc" size="60"></u-icon>
        <text class="empty-text">暂无消息</text>
      </view>
    </scroll-view>

    <!-- Toast提示 -->

  </view>
</template>

<script>
export default {
  data() {
    return {
      statusBarHeight: 0,
      refreshing: false,
      loading: false,

      // 未读消息数量
      systemUnreadCount: 2,
      likeUnreadCount: 5,
      commentUnreadCount: 3,
      followUnreadCount: 1,
      atUnreadCount: 2,

      // 系统消息预览
      systemMessagePreview: '您的帖子获得了新的点赞',

      // 最近消息列表
      recentMessages: []
    }
  },

  onLoad() {
    this.initPage()
  },

  onShow() {
    this.loadRecentMessages()
  },

  methods: {
    // 初始化页面
    async initPage() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 0

      await this.loadRecentMessages()
      await this.loadUnreadCounts()
    },

    // 加载最近消息
    async loadRecentMessages() {
      this.loading = true

      try {
        // 这里应该调用API获取最近消息
        // const res = await this.$api.getRecentMessages()

        // 模拟数据
        this.recentMessages = this.generateMockMessages()
      } catch (error) {
        console.error('加载消息失败:', error)
        this.showToast('加载失败，请重试', 'error')
      } finally {
        this.loading = false
      }
    },

    // 加载未读消息数量
    async loadUnreadCounts() {
      try {
        // 这里应该调用API获取未读消息数量
        // const res = await this.$api.getUnreadCounts()

        // 模拟数据已在data中设置
      } catch (error) {
        console.error('加载未读数量失败:', error)
      }
    },

    // 生成模拟消息数据
    generateMockMessages() {
      const messages = []
      const types = ['like', 'comment', 'follow', 'at']
      const usernames = ['小明', '小红', '小李', '小王', '小张']

      for (let i = 0; i < 8; i++) {
        const type = types[i % types.length]
        const message = {
          id: Date.now() + i,
          type: type,
          username: usernames[i % usernames.length],
          userAvatar: `https://cdn.uviewui.com/uview/album/${(i % 6) + 1}.jpg`,
          create_time: new Date(Date.now() - Math.random() * 86400000 * 3).toISOString(),
          isRead: Math.random() > 0.4,
          relatedContent: {
            content: '今天天气真好，出去拍了一些照片分享给大家',
            image: Math.random() > 0.5 ? `https://cdn.uviewui.com/uview/album/${(i % 6) + 1}.jpg` : null
          }
        }
        messages.push(message)
      }

      return messages.sort((a, b) => new Date(b.create_time) - new Date(a.create_time))
    },

    // 获取消息类型图标
    getMessageTypeIcon(type) {
      const icons = {
        like: 'heart-fill',
        comment: 'chat-fill',
        follow: 'account-fill',
        at: 'at'
      }
      return icons[type] || 'bell-fill'
    },

    // 获取消息文本
    getMessageText(message) {
      const texts = {
        like: '点赞了你的帖子',
        comment: '评论了你的帖子',
        follow: '关注了你',
        at: '在评论中@了你'
      }
      return texts[message.type] || '发送了一条消息'
    },

    // 格式化时间
    formatTime(timeStr) {
      const time = new Date(timeStr)
      const now = new Date()
      const diff = now - time

      if (diff < 60000) return '刚刚'
      if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
      if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前'
      if (diff < 604800000) return Math.floor(diff / 86400000) + '天前'

      return time.toLocaleDateString()
    },

    // 下拉刷新
    async onRefresh() {
      this.refreshing = true
      await Promise.all([
        this.loadRecentMessages(),
        this.loadUnreadCounts()
      ])
      this.refreshing = false
    },

    // 事件处理方法
    handleSettings() {
      this.$tab.navigateTo('/pages/message/settings')
    },

    handleSystemMessage() {
      this.$tab.navigateTo('/pages/message/system')
    },

    handleLikeMessages() {
      this.$tab.navigateTo('/pages/message/likes')
    },

    handleCommentMessages() {
      this.$tab.navigateTo('/pages/message/comments')
    },

    handleFollowMessages() {
      this.$tab.navigateTo('/pages/message/follows')
    },

    handleAtMessages() {
      this.$tab.navigateTo('/pages/message/mentions')
    },

    handleAllMessages() {
      this.$tab.navigateTo('/pages/message/all')
    },

    handleMessageDetail(message) {
      // 标记为已读
      message.isRead = true

      // 根据消息类型跳转到相应页面
      switch (message.type) {
        case 'like':
        case 'comment':
        case 'at':
          this.$tab.navigateTo(`/pages/post/detail?id=${message.relatedContent.postId}`)
          break
        case 'follow':
          this.$tab.navigateTo(`/pages/user/profile?uid=${message.userId}`)
          break
        default:
          this.showToast('消息详情功能开发中', 'info')
      }
    },

    showToast(title, type = 'default') {
      // 使用 uView 2.0 的 toast 方法
      this.$u.toast(title)
    }
  }
}
</script>

<style lang="scss" scoped>
.message-container {
  min-height: 100vh;
  background: #f8f9fa;
}

.custom-navbar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;

  .navbar-content {
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 15px;

    .navbar-title {
      font-size: 18px;
      font-weight: 600;
      color: white;
    }

    .navbar-right {
      display: flex;
      align-items: center;
    }
  }
}

.main-content {
  
  height: calc(100vh - 88px);
  padding-left: 15px;
  padding-right: 15px;
}

.system-messages {
  margin-bottom: 15px;
  padding: 0;

  .message-item {
    display: flex;
    align-items: center;
    padding: 15px;

    .message-icon {
      width: 45px;
      height: 45px;
      border-radius: 22.5px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 12px;

      &.system {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }
    }

    .message-content {
      flex: 1;

      .message-title {
        font-size: 15px;
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 4px;
      }

      .message-desc {
        font-size: 13px;
        color: #999;
        display: block;
      }
    }

    .message-meta {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
}

.message-categories {
  background: white;
  border-radius: 15px;
  padding: 20px;
  margin-bottom: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);

  .category-grid {
    display: flex;
    justify-content: space-between;

    .category-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      position: relative;
      flex: 1;

      .category-icon {
        width: 50px;
        height: 50px;
        border-radius: 25px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 8px;

        &.like {
          background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
        }

        &.comment {
          background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
        }

        &.follow {
          background: linear-gradient(135deg, #45b7d1 0%, #96c93d 100%);
        }

        &.at {
          background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
      }

      .category-title {
        font-size: 12px;
        color: #666;
        text-align: center;
      }
    }
  }
}

.recent-messages {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }

    .section-more {
      font-size: 14px;
      color: #667eea;
    }
  }

  .message-list {
    .message-item {
      display: flex;
      align-items: flex-start;
      padding: 15px;
      margin-bottom: 10px;

      .message-avatar {
        position: relative;
        margin-right: 12px;

        .message-type-badge {
          position: absolute;
          bottom: -2px;
          right: -2px;
          width: 20px;
          height: 20px;
          border-radius: 10px;
          display: flex;
          align-items: center;
          justify-content: center;
          border: 2px solid white;

          &.like {
            background: #ff6b6b;
          }

          &.comment {
            background: #4ecdc4;
          }

          &.follow {
            background: #45b7d1;
          }

          &.at {
            background: #f093fb;
          }
        }
      }

      .message-content {
        flex: 1;

        .message-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 6px;

          .message-username {
            font-size: 14px;
            font-weight: 600;
            color: #333;
          }

          .message-time {
            font-size: 12px;
            color: #999;
          }
        }

        .message-text {
          font-size: 13px;
          color: #666;
          margin-bottom: 8px;
          display: block;
        }

        .message-preview {
          background: #f8f9fa;
          border-radius: 8px;
          padding: 10px;
          display: flex;
          align-items: center;
          gap: 10px;

          .preview-text {
            flex: 1;
            font-size: 12px;
            color: #999;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .preview-image {
            width: 40px;
            height: 40px;
            border-radius: 6px;
          }
        }
      }

      .message-status {
        margin-left: 8px;

        .unread-dot {
          width: 8px;
          height: 8px;
          border-radius: 4px;
          background: #ff4757;
        }
      }
    }
  }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;

  .empty-text {
    font-size: 16px;
    color: #999;
    margin-top: 20px;
    display: block;
  }
}
</style>
